//
//  HZL_RecommendViewController.m
//  B_Project
//
//  Created by 胡佳俊 on 15/11/28.
//  Copyright © 2015年 HZL. All rights reserved.
//

#import "HZL_RecommendViewController.h"
#import "HZL_HeaderScrollView.h"
#import "HZL_RecommendIndexTableViewCell.h"
#import "HZL_StoryCollectionTabelViewCell.h"
#import "HZL_headerScrollWebViewController.h"
#import "HZL_RecommendModel.h"
#import "HZL_StoryItemCollectionViewCell.h"
#import "MJRefresh.h"
#import "HZL_StoryDetailTableViewCell.h"
#import "HZL_StoryDetailPageViewController.h"
#import "HZL_StoryAllPageViewController.h"
#import "HZL_TravelNotesDetailPageViewController.h"
#import "HZL_NearbyViewController.h"
#import <MapKit/MapKit.h>
#import "AMapNaviKit.h"
#import "RESideMenu.h"
@interface HZL_RecommendViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, jumpToWebView, CLLocationManagerDelegate>

@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, assign)NSInteger height; // 接受每个游记cell行高
@property (nonatomic, retain)NSMutableArray *dataArr; //推荐首页总数组
@property (nonatomic, retain)NSMutableArray *ScrollViewDataArr;
@property (nonatomic, retain)NSMutableArray *storyArr;
@property (nonatomic, retain)NSMutableArray *modelStoryDataArr; //转化为model的story数组
@property (nonatomic, retain)NSMutableArray *modelUserDataArr; // 转化为model的story中的user数组
@property (nonatomic, retain)NSMutableArray *modelTravelDataArr;
@property (nonatomic, retain)NSMutableArray *modelTravelUserArr;
@property (nonatomic, retain)NSMutableArray *modelDetailStoryArr;//转化为对象的故事详情数组
@property (nonatomic, retain)UIView *viewTitle1; //第一个分区头view
@property (nonatomic, retain)NSNumber *next_start; //下一页数据

@property (nonatomic, retain)UISearchBar *searchBar;
@property (nonatomic, retain)NSMutableArray *modelSearchArr;
@property (nonatomic, retain)NSMutableArray *modelSearchElementsArr;
@property (nonatomic, retain)UIView *nightView;
@property (nonatomic, retain)UIView *headerView;
@property (nonatomic, retain)HZL_HeaderScrollView *headerScrollView;  //轮播图

// 地图
@property (nonatomic, retain) CLLocation *loaction;
@property (nonatomic, retain) CLLocationManager *manager;
@end

@implementation HZL_RecommendViewController
#pragma mark - 网络状态判断
- (void)netJudge
{
    //网络状态判断
    [HZL_NetworkingHandle networkReachabilityStatus:^(id r) {
        //判断网络是否有wifi 如果没有WiFi建议在WiFi下使用
        if (![r isEqualToNumber:@2]) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"当前是非WiFi环境 建议在WiFi下使用" preferredStyle:UIAlertControllerStyleAlert];
            //获取app的根视图
            UIWindow *app = [UIApplication sharedApplication].keyWindow;
            [app.rootViewController presentViewController:alert animated:YES completion:nil];
            //提示在一秒后消失
            [self performSelector:@selector(removeAlert) withObject:alert afterDelay:2];
        }
    }];
}
#pragma mark - 移除WiFi提示
- (void)removeAlert
{
    //alertView消失
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    ////当控制器上存在滑动视图时 给滑动视图添加上边距(0 , 64)
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.view.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
//    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"附近" style:UIBarButtonItemStylePlain target:self action:@selector(nearbyAction)];
    
   self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-liebiao"] style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController:)];
    // 定位
    self.manager = [[CLLocationManager alloc] init];
    // 当用到才定位
    [self.manager requestAlwaysAuthorization];
    self.manager.delegate = self;
    // 距离过滤
    self.manager.distanceFilter = 50;
    // 定位精度
    self.manager.desiredAccuracy = kCLLocationAccuracyBest;
    // 开始定位
    [self.manager startUpdatingLocation];
    
    [self getData];
    
    [self loadMBProgress];
}
- (void)nearbyAction
{
    HZL_NearbyViewController *nVC = [[HZL_NearbyViewController alloc] init];
    nVC.latitude = self.loaction.coordinate.latitude;
    nVC.longitude = self.loaction.coordinate.longitude;
    nVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:nVC animated:YES];

}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    // 最新的位置信息
    self.loaction = [locations lastObject];
}
#pragma mark - 获取推荐首页数据
- (void)getData
{
    NSString *url = @"http://api.breadtrip.com/v2/index/?lat=38.8802706535603&lng=121.54089204778&sign=dfcaa3638dd2a27e24a726ba2d2fd3cd";
    [HZL_NetworkingHandle getUrl:url cookie:nil result:^(id result) {
        //接收总字典
        NSMutableDictionary *tempDic = result;
        if (tempDic.count == 0) {
//            [self JudgeNet];
            return ;
        }
        //下一页id
        self.next_start = tempDic[@"data"][@"next_start"];
        
        //首页总数据
        self.dataArr = tempDic[@"data"][@"elements"];
        self.ScrollViewDataArr = [NSMutableArray array];
        //轮播图数组
        for (NSMutableDictionary  *dic in [self.dataArr[0] objectForKey:@"data"][0]) {
            //   if ([dic[@"platform"] isEqualToString:@"all"]) {
            [self.ScrollViewDataArr addObject:dic];
            // }
        }
        ///搜索页数据
        self.modelSearchArr = [HZL_RecommendModel transformWithArray:tempDic[@"data"][@"search_data"]];
        self.modelSearchElementsArr = [NSMutableArray array];
        for (NSMutableDictionary *dic in tempDic[@"data"][@"search_data"] ) {
            [self.modelSearchElementsArr addObject: [HZL_RecommendModel transformWithArray:dic[@"elements"]]];
            
        }
        
        
        
        
#if 1   /*story数据   */
        //创建一个数组 用来存放所有type == 10的字典
        NSMutableArray *typeArr = [NSMutableArray array];
        for (NSDictionary *dic in self.dataArr) {
            
            NSString *type = [NSString stringWithFormat:@"%@", dic[@"type"]];
            if ([type isEqualToString:@"10"]) {
                [typeArr addObject:dic];
            }
        }
        
        
        //创建一个数组 用来接收四个view的数据
        NSMutableArray *typeDataArr = [NSMutableArray array];
        for (NSDictionary *dic in typeArr) {
            [typeDataArr addObject: dic[@"data"][0]];
        }
        
        //创建一个数组 用来接收四个view中user信息的数据
        NSMutableArray *typeUserArr = [NSMutableArray array];
        for (NSDictionary *dic in typeDataArr) {
            [ typeUserArr addObject: dic[@"user"]];
        }
        
        
        self.modelStoryDataArr = [HZL_RecommendModel transformWithArray:typeDataArr];
        self.modelUserDataArr = [HZL_RecommendModel transformWithArray:typeUserArr];
#endif
        
#if 1   /* 游记数据  */
        //创建一个数组 用来存放所有type == 4的字典
        NSMutableArray *travelArr = [NSMutableArray array];
        for (NSDictionary *dic in self.dataArr) {
            
            NSString *type = [NSString stringWithFormat:@"%@", dic[@"type"]];
            if ([type isEqualToString:@"4"]) {
                [travelArr addObject:dic];
                // NSLog(@"%@",  dic[@"data"][0] [@"name"]);
            }
        }
        
        
        //创建一个数组 用来接收view的数据
        NSMutableArray *travelDataArr = [NSMutableArray array];
        for (NSDictionary *dic in travelArr) {
            [travelDataArr addObject: dic[@"data"][0]];
        }
        
        //创建一个数组 用来接收四个view中user信息的数据
        NSMutableArray *travelUserArr = [NSMutableArray array];
        for (NSDictionary *dic in travelDataArr) {
            [travelUserArr addObject: dic[@"user"]];
        }
        
        self.modelTravelDataArr = [HZL_RecommendModel transformWithArray:travelDataArr];
        self.modelTravelUserArr = [HZL_RecommendModel transformWithArray:travelUserArr];
        
#endif
        
        if (self.tableView == nil) {
            //创建tableView
            [self createMainTableView];
        }
        
        else
        {
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
        }
        
        [self.hud removeFromSuperview];
    }];
    
}

#pragma mark - 创建tableView
- (void)createMainTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, VIEW_WIDTH, VIEW_HEIGHT - 64) style:UITableViewStyleGrouped];
    
    self.tableView.scrollsToTop = YES;
    
    self.tableView.delegate = self;
    self.tableView.dataSource =self;
    self.tableView.tableFooterView = [UIView new];
    [self.view addSubview:self.tableView];
    
    if (self.ScrollViewDataArr.count != 0) {
        // 创建轮播图
        [self createHeaderScrollView];
    }
    [self MJRefresh];
}
#pragma mark - MJ刷新
- (void)MJRefresh
{
    //MJ下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self getData];
    }];
    //上拉加载
    self.tableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        NSString *url = [ NSString stringWithFormat:@"http://api.breadtrip.com/v2/index/?next_start=%@", self.next_start];
        [HZL_NetworkingHandle getUrl:url cookie:nil result:^(id result) {

            NSMutableDictionary *dic = result;
            //接收总字典
            NSMutableDictionary *tempDic = result;
            
            //下一页id
            self.next_start = tempDic[@"data"][@"next_start"];
            
            
            NSMutableArray *tempArr =  dic[@"data"][@"elements"];
            
            //创建一个数组 用来存放所有type == 4的字典
            NSMutableArray *travelArr = [NSMutableArray array];
            for (NSDictionary *dic in tempArr) {
                
                NSString *type = [NSString stringWithFormat:@"%@", dic[@"type"]];
                if ([type isEqualToString:@"4"]) {
                    [travelArr addObject:dic];
                }
            }
            
            
            //创建一个数组 用来接收view的数据
            NSMutableArray *travelDataArr = [NSMutableArray array];
            for (NSDictionary *dic in travelArr) {
                [ travelDataArr addObject: dic[@"data"][0]];
            }
            
            
            //把之后页面的对象数组中的对象 加到原对象数组中
            [self.modelTravelDataArr addObjectsFromArray:[HZL_RecommendModel transformWithArray:travelDataArr]];
            
            //user数据加到原对象数组中
            NSMutableArray *userDataArr = [NSMutableArray array];
            for (NSDictionary *dic in tempArr) {
                NSMutableDictionary *tempDic = dic[@"data"][0][@"user"];
                [userDataArr addObject:tempDic];
            }
            [self.modelTravelUserArr addObjectsFromArray:[HZL_RecommendModel transformWithArray:userDataArr]];
            [self.tableView.mj_footer endRefreshing];
            [self.tableView reloadData];
        }];
    }];
    
}


#pragma mark - 创建轮播图
- (void)createHeaderScrollView
{
    self.headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 200)];
    self.tableView.tableHeaderView = self.headerView;
    self.headerScrollView = [[HZL_HeaderScrollView alloc]initWithFrame:self.headerView.frame dataArr:self.ScrollViewDataArr];
    //设置代理人
    self.headerScrollView.delegate = self;
    
    [self.headerView addSubview:self.headerScrollView];
}


#pragma mark - 轮播图实现协议方法
- (void)jumptoWebView:(NSString *)str
{
    HZL_headerScrollWebViewController *webView = [[HZL_headerScrollWebViewController alloc]init];
    webView.urlStr = str;
    webView.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webView animated:YES];
}


#pragma mark - 分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}


#pragma mark - 分区头部高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 44;
    }
    else
    {
        return 34;
    }
    
}
#pragma mark - 分区头view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
#pragma mark - 第一个section的分区头view
    self.viewTitle1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT)];;
    
    UILabel *blueLable = [[UILabel alloc]initWithFrame:CGRectMake(10, 10 , 5, 24)];
    blueLable.backgroundColor = [UIColor colorWithRed:0.35 green:0.73 blue:0.78 alpha:1];
    [self.viewTitle1 addSubview:blueLable];
    blueLable.layer.masksToBounds = YES;
    blueLable.layer.cornerRadius = 2;
    
    
    UILabel *titleLable = [[UILabel alloc]initWithFrame:CGRectMake(25, 10, VIEW_WIDTH - 25 , blueLable.frame.size.height)];
    titleLable.textColor = [UIColor darkGrayColor];
    titleLable.font = [UIFont fontWithName:@"Arial-Bold" size:15];
    titleLable.text = self.dataArr[1][@"data"][0][@"title"];
    
    [self.viewTitle1 addSubview:titleLable];
    //全部按钮
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame =CGRectMake(VIEW_WIDTH - 90, 10, 90, blueLable.frame.size.height);
    
    [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [btn setTitle:@"全部" forState:UIControlStateNormal];
    [self.viewTitle1 addSubview:btn];
    [btn addTarget:self action:@selector(allPageAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *imgAllRight = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"allRight"]];
    imgAllRight.frame = CGRectMake(65, 3, 20, btn.frame.size.height - 5);
    
    [btn addSubview:imgAllRight];

#pragma mark - 第二个section的分区头view
    UIView *viewTitle2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT)];
    
    UILabel *blueLable1 = [[UILabel alloc]initWithFrame:CGRectMake(10, 0 , 5, 24)];
    blueLable1.backgroundColor = [UIColor colorWithRed:0.35 green:0.73 blue:0.78 alpha:1];
    [viewTitle2 addSubview:blueLable1];
    blueLable1.layer.masksToBounds = YES;
    blueLable1.layer.cornerRadius = 2;
    
    UILabel *titleLable1 = [[UILabel alloc]initWithFrame:CGRectMake(25, 0, VIEW_WIDTH - 25 , blueLable1.frame.size.height)];
    titleLable1.textColor = [UIColor darkGrayColor];
    titleLable1.font = [UIFont fontWithName:@"Arial-Bold" size:15];
    titleLable1.text =  self.dataArr[6][@"data"][0][@"title"];
    
    [viewTitle2 addSubview:titleLable1];
    
    if (section == 0) {
        @autoreleasepool {
            return self.viewTitle1;
        }
        
    }
    else
    {
        @autoreleasepool {
            return viewTitle2;
        }
        
    }
    
}



#pragma mark - 故事分区全部按钮触发事件
- (void)allPageAction
{
    HZL_StoryAllPageViewController *story = [[HZL_StoryAllPageViewController alloc]init];
    story.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:story animated:YES];
}

#pragma mark - tableView  分行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    else
    {
        return self.modelTravelDataArr.count;
    }
    
}

#pragma mark - tableView 数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //每日精选故事数据
    if (indexPath.section == 0) {
        HZL_StoryCollectionTabelViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"story"];
        if (!cell) {
            cell = [[HZL_StoryCollectionTabelViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"story"];
        }
        cell.delegate = self;
        cell.dataSource = self;
        [cell.collectionView reloadData];
        return cell;
    }
    //游记数据
    else
    {
        HZL_RecommendIndexTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"travel"];
        if (!cell) {
            cell = [[HZL_RecommendIndexTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"travel"];
        }
        cell.travelModel = self.modelTravelDataArr[indexPath.row];
        cell.travelUserModel = self.modelTravelUserArr[indexPath.row] ;
        
        return cell;
    }
}


#pragma mark - tableView Cell 点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //游记分区
    if (indexPath.section == 1) {
        HZL_TravelNotesDetailPageViewController *travelNotes = [[HZL_TravelNotesDetailPageViewController alloc]init];
        
        travelNotes.travelNotesModel = self.modelTravelDataArr[indexPath.row];
        
        //收藏时 把前一页的对象传递过去  用来获取图片文字
        travelNotes.recommendModel = self.modelTravelDataArr[indexPath.row];
        travelNotes.recommentUserModel = self.modelTravelUserArr[indexPath.row];
        
        travelNotes.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:travelNotes animated:YES];
    }
}

#pragma mark - tableView行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 550;
    }
    else{
        HZL_RecommendModel *tempModel = self.modelTravelDataArr[indexPath.row];
        
        //自适应标题
        CGFloat HTitleLable = [[self class]heightWithText:tempModel.name fontSize:18 Width:VIEW_WIDTH - 40];
        
        return    5 + 10 + HTitleLable + 10 + 15 + 5 + 15 + VIEW_WIDTH / 4 + 10 + 10 + (VIEW_WIDTH - 20) / 6;
        
    }
}

#pragma mark - 协议方法 item个数

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HZL_StoryItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"StoryItemitem" forIndexPath:indexPath];
    
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"isNight"])
    {
        cell.backgroundColor = [UIColor blackColor];
        
        
    }
    else
    {
        cell.backgroundColor = [UIColor whiteColor];
    }
    
    
    cell.recommendModel = self.modelStoryDataArr[indexPath.item];
    cell.userModel = self.modelUserDataArr[indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    HZL_StoryDetailPageViewController *storyDetail = [[HZL_StoryDetailPageViewController alloc]init];
    storyDetail.spot_id = ((HZL_RecommendModel *)self.modelStoryDataArr[indexPath.item]).spot_id;
    
    //收藏时拿到前页数据
    storyDetail.recommendModel = self.modelStoryDataArr[indexPath.item];
    storyDetail.userModel = self.modelUserDataArr[indexPath.item];
    
    storyDetail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:storyDetail animated:YES];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
